package com.lsl.controller;

import com.lsl.entity.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file-service")
public class FileController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.access-url}")
    private String accessUrl;

    @PostMapping("/upload")
    public Result<String> uploadFile(
            @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error(400, "文件不能为空");
        }
        try {
            // 创建上传目录
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 获取文件名
            String filename = file.getOriginalFilename();
            // 保存文件
            File dest = new File(dir, filename);
            file.transferTo(dest);
            // 检查文件是否成功保存
            if (!dest.exists()) {
                return Result.error(500, "文件上传失败");
            }
            // 返回访问URL
            String fileUrl = accessUrl + "/" + filename;
            return Result.success(fileUrl);
        } catch (IOException e) {
            return Result.error(500, "文件上传失败" + e.getMessage());
        }
    }

}